$(function() {

	var $loginCode = $('#loginCode');
	var $loginPassword = $('#loginPassword');
	var $rememberMe = $('#rememberMe');
	var $loginButton = $('#loginButton');
	var $myModal = $('#myModal');
	var $noLogin = $('#noLogin');
	var $logined = $('#logined');
	var $loginedTpl = $('#loginedTpl');
	var $logout = $('#logout');

	/**
	 * 页面重新加载的时候，回显登录信息
	 */
	var userCode = sessionStorage.getItem('code');
	var userPhoto = sessionStorage.getItem('photo');
	if (userCode) {
		renderLoginInfo({
			code: userCode,
			photo: userPhoto
		});
	};

	/**
	 * 打开页面时，如果用户没有登录就自动登录
	 */
	var loginCode = localStorage.getItem('loginCode');
	var loginPassword = localStorage.getItem('loginPassword');
	if (!userCode && loginCode) {
		var param = {
			'code': loginCode,
			'password': loginPassword,
			'date': new Date().getTime()
		}
		$.get(common.path + 'login', param, function(data) {
			if (data.code == 200) {
				layer.msg('登录成功！');

				renderLoginInfo(data.result);

				// 把登录信息放到了sessionStorage对象中
				sessionStorage.setItem('code', data.result.code);
				sessionStorage.setItem('photo', data.result.photo);
				sessionStorage.setItem('token', data.result.token);
			} else {
				layer.msg(data.reason);
			}
		})
	}

	/**
	 * 退出系统
	 */
	$(document).on('click', '#logout', function() {
		sessionStorage.removeItem('code');
		sessionStorage.removeItem('photo');
		sessionStorage.removeItem('token');

		localStorage.removeItem('loginCode');
		localStorage.removeItem('loginPassword');
		localStorage.removeItem('rememberMe');
		
		if(/Background\.html/.test(location.pathname)){
			location = 'index.html';
		}else{
			location.reload();
		}

		location.reload();
		layer.msg('退出成功！');
	});

	/**
	 * 登录的相关功能
	 */
	$loginButton.click(function() {
		// setLoginInfoToCookie();

		// 点击自动登录后把用户信息记录到localStorage里
		if ($rememberMe.prop('checked')) {
			localStorage.setItem('loginCode', $loginCode.val().trim());
			localStorage.setItem('loginPassword', $loginPassword.val().trim());
			localStorage.setItem('rememberMe', $rememberMe.val().trim());
		} else {
			localStorage.removeItem('loginCode');
			localStorage.removeItem('loginPassword');
			localStorage.removeItem('rememberMe');
		}

		// 执行登录
		var $btn = $(this).button('loading')
		var param = {
			'code': $loginCode.val().trim(),
			'password': $loginPassword.val().trim(),
			'date': new Date().getTime()
		}
		$.get(common.path + 'login', param, function(data) {
			if (data.code == 200) {
				$btn.button('reset')
				$myModal.modal('hide');
				layer.msg('登录成功！');

				renderLoginInfo(data.result);

				// 把登录信息放到了sessionStorage对象中
				sessionStorage.setItem('code', data.result.code);
				sessionStorage.setItem('photo', data.result.photo);
				sessionStorage.setItem('token', data.result.token);
			} else {
				$btn.button('reset')
				layer.msg(data.reason);
			}
		})
	});

	/**
	 * 回显用户登录信息
	 * 
	 * @param {Object} data
	 */
	function renderLoginInfo(data) {
		$noLogin.hide();
		$logined.show();
		// 解析模板
		var compiled = _.template($loginedTpl.html());
		// 将返回的函数存储起来（就像我将它存储在compiled变量中一样），再通过调用该函数来渲染数据，特别是在同一个模板可能会被多次渲染的情况下，这样做能提高执行效率
		var html = compiled({
			user: data
		});
		$logined.append(html);
	}

	// 记住密码的功能实现
	/*
		var loginCodeInCookie = $.cookie('loginCode');
		var loginPasswordInCookie = $.cookie('loginPassword');
		var rememberMeInCookie = $.cookie('rememberMe');
		if (loginCodeInCookie) {
			$loginCode.val(loginCodeInCookie);
		}
		if (loginPasswordInCookie) {
			$loginPassword.val(loginPasswordInCookie);
		}
		if (rememberMeInCookie) {
			$rememberMe.prop('checked', true);
		}
	
		function setLoginInfoToCookie() {
			if ($rememberMe.prop('checked')) {
				// jquery.cookie.js的更多使用，请参考：http://www.cnblogs.com/afuge/archive/2013/07/03/3169048.html
				$.cookie('loginCode', $loginCode.val(), {
					expires: 7
				});
				$.cookie('loginPassword', $loginPassword.val(), {
					expires: 7
				});
				$.cookie('rememberMe', $rememberMe.val(), {
					expires: 7
				});
			} else {
				$.cookie('loginCode', null);
				$.cookie('loginPassword', null);
				$.cookie('rememberMe', null);
			}
		}
	*/

	/**
	 *  注册的相关功能
	 */
	var $myModal1 = $('#myModal1');
	var $registerCode = $('#registerCode');
	var $registerPassword = $('#registerPassword');
	var $registerConfirmPassword = $('#registerConfirmPassword');
	var $registerBtn = $('#registerBtn');

	// 模态框显示时光标聚焦
	$myModal1.on('show.bs.modal', function(e) {});

	// 模态框隐藏时把内容清除掉
	$myModal1.on('hidden.bs.modal', function(e) {
		$registerCode.val('');
		$registerCode.parent().removeClass().addClass('form-group');
		$registerCode.nextAll().remove();
		$registerPassword.val('');
		$registerPassword.parent().removeClass().addClass('form-group');
		$registerPassword.nextAll().remove();
		$registerConfirmPassword.val('');
		$registerConfirmPassword.parent().removeClass().addClass('form-group');
		$registerConfirmPassword.nextAll().remove();
	});

	// 注册前验证
	var hasErrorAndFeedback = 'form-group has-error has-feedback';
	var hasSuccessAndFeedback = 'form-group has-success has-feedback';
	var hasErrorIcon = '<span class="glyphicon glyphicon-remove form-control-feedback"></span>';
	var hasSuccessIcon = '<span class="glyphicon glyphicon-ok form-control-feedback"></span>';
	// 针对账号的验证
	var setTimeoutId;
	$registerCode.keyup(function() {
		clearTimeout(setTimeoutId);
		setTimeoutId = setTimeout(function() {
			validateRegisterCode();
		}, 300)
	});

	function validateRegisterCode() {
		var registerCodeVal = $registerCode.val().trim();
		if (registerCodeVal === '') {
			$registerCode.parent().removeClass().addClass(hasErrorAndFeedback);
			$registerCode.nextAll().remove();
			$registerCode.after(hasErrorIcon + '<div class="invalid">帐号不能为空！</div>');
			return false;
		} else if (registerCodeVal.length > 12) {
			$registerCode.parent().removeClass().addClass(hasErrorAndFeedback);
			$registerCode.nextAll().remove();
			$registerCode.after(hasErrorIcon + '<div class="invalid">帐号不能长于12位！</div>');
			return false;
		} else {
			// 当帐号在JS端验证通过时，再向服务器请求，此帐号是否存在
			$.get(common.path + 'isExist', {
				code: registerCodeVal,
				random: Math.random()
			}, function(data) {
				if (data.code == 200) {
					$registerCode.parent().removeClass().addClass(hasSuccessAndFeedback);
					$registerCode.nextAll().remove();
					$registerCode.after(hasSuccessIcon);
					$registerBtn.prop('disabled', false);
				} else {
					$registerCode.parent().removeClass().addClass(hasErrorAndFeedback);
					$registerCode.nextAll().remove();
					$registerCode.after(hasErrorIcon + '<div class="invalid">帐号已存在！</div>');
					$registerBtn.prop('disabled', true);
				}
			});
			return true;
		}
	}

	// 针对密码的验证
	$registerPassword.keyup(function() {
		validateRegisterPassword();
		validateRegisterConfirmPassword();
	});

	function validateRegisterPassword() {
		var registerPasswordVal = $registerPassword.val().trim();
		if (registerPasswordVal.length > 12 || registerPasswordVal.length < 6) {
			$registerPassword.parent().removeClass().addClass(hasErrorAndFeedback);
			$registerPassword.nextAll().remove();
			$registerPassword.after(hasErrorIcon + '<div class="invalid">密码必须在6~12位之间！</div>');
			return false;
		} else {
			$registerPassword.parent().removeClass().addClass(hasSuccessAndFeedback);
			$registerPassword.nextAll().remove();
			$registerPassword.after(hasSuccessIcon);
			return true;
		}
	}
	// 针对确认密码的验证
	$registerConfirmPassword.keyup(function() {
		validateRegisterConfirmPassword();
	});

	function validateRegisterConfirmPassword() {
		var registerPasswordVal = $registerPassword.val().trim();
		var registerConfirmPasswordVal = $registerConfirmPassword.val().trim();
		if (registerConfirmPasswordVal != registerPasswordVal) {
			$registerConfirmPassword.parent().removeClass().addClass(hasErrorAndFeedback);
			$registerConfirmPassword.nextAll().remove();
			$registerConfirmPassword.after(hasErrorIcon + '<div class="invalid">确认密码必须与原密码一致！</div>');
			return false;
		} else {
			$registerConfirmPassword.parent().removeClass().addClass(hasSuccessAndFeedback);
			$registerConfirmPassword.nextAll().remove();
			$registerConfirmPassword.after(hasSuccessIcon);
			return true;
		}
	}

	// 进行注册
	$registerBtn.click(function() {
		var result = true;

		if (!validateRegisterCode() | !validateRegisterPassword() | !validateRegisterConfirmPassword()) {
			result = false;
		}

		// 验证成功后提交
		if (result) {
			var $btn = $(this).button('loading')
			var param = {
				'user.code': $registerCode.val().trim(),
				'user.password': $registerPassword.val().trim(),
				'date': new Date().getTime()
			}
			$.get(common.path + 'register', param, function(data) {
				if (data.code == 200) {
					$btn.button('reset')
					$myModal1.modal('hide');
					layer.msg('注册成功！');
				} else {
					$btn.button('reset')
					layer.msg('注册失败！可能的原因是：' + data.reason);
				}
			})
		}
	});
});